<script setup>
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

import {UseChatStore, UseSocketStore, UseUserStore} from '@/stores/index.js'

let socketStore = UseSocketStore()
let userStore = UseUserStore()
let chatStore = UseChatStore()
dayjs.locale('zh-cn') // 全局使用简体中文
dayjs.extend(relativeTime)
const textareaVal = ref('')

const userid = 'root'
const chatArr = ref([])

const scrollListRef = ref(null)

// 比较时间戳方法
function compareTimestamps(index) {
  const currentTimestamp = chatArr.value[index].time;
  const prevTimestamp = index > 0 ? chatArr.value[index - 1].time : 0;

  if (index === 0 || currentTimestamp - prevTimestamp > 180000) {
    return dayjs(currentTimestamp).format('YYYY-MM-DD HH:mm:ss');
  } else {
    return dayjs(prevTimestamp).from(dayjs(currentTimestamp));
  }
}

// 判断两个时间是否小于1分钟，小于一分钟就返回 true，否则返回 false
function compareTimestampsIsShow(index) {
  const currentTimestamp = chatArr.value[index].time;
  const prevTimestamp = index > 0 ? chatArr.value[index - 1].time : 0;
  const diffInMinutes = Math.abs((currentTimestamp - prevTimestamp) / 60000);

  if (index === 0 || diffInMinutes < 1) {
    return true;
  } else {
    return false;
  }
}


function sendMsg() {
  console.log('发送信息')
  chatStore.chat.textarea = textareaVal.value
  let chatInfo = {
    userid: socketStore.userInfo.id,
    name: socketStore.userInfo.userName,
    message: textareaVal.value,
    time: new Date(),
    role: socketStore.userInfo.role,
    roomId: userStore.userInfo.roomId,
    avator: userStore.userInfo.avator
  }
  sendSocketMsg(chatInfo)
  textareaVal.value = ''
}


// 加入房间
function joinRoom() {
}

// 离开房间
function leaveRoom() {
}

// 断开连接


watch(() => chatArr.value, (newVal) => {
  if (newVal) {
    console.log('new', newVal)
    scrollToBottom()

    nextTick(() => {
      scrollToBottom();
    });
  }
})

// 发送消息
function sendSocketMsg(data) {
  // scrollList.value.scrollTop = scrollList.value.scrollHeight
  scrollToBottom()
  socketStore.socket.emit('message', data)

  nextTick(() => {
    scrollToBottom();
  });
}

// 接收
function receiveSocketMsg() {
  socketStore.socket.on('message', (data) => {
    console.log('收到服务端传来的聊天数据', data)
    chatArr.value = data
  })
}

receiveSocketMsg()
// 滚动到底部
const scrollToBottom = () => {
  const element = scrollListRef.value;
  if (element) {
    element.scrollTop = 999999999999999
  }
};
</script>


<template>
  <div class="h-4/6 w-full  mt-7 ">
    <h4 class="font-medium text-xl mb-1">聊天(28)</h4>
    <div class=" h-9/10">
      <div id="scrollList" ref="scrollListRef" class="h-5/6 custom-scrollbar overflow-x-auto p-1">
        <div v-if="chatArr.length===0" class="time w-full h-10  text-center leading-10">
          <p>当前没有人发起聊天,快来开始吧</p>
        </div>
        <template v-for="(item,index) in chatArr">

          <div v-if="!compareTimestampsIsShow(index)" class="time w-full h-10  text-center leading-10">
            <p>{{ compareTimestamps(index) }}</p>
          </div>
          <!--              我自己-->
          <div v-if="item.userid === userStore.userInfo.id">
            <div class="flex justify-end  mb-3">
              <div class="w-4/6 ">
                <div class="flex justify-end">{{ item.name }}</div>
                <div
                    class="flex justify-end">
                  <p class="min-w-10 p-2.5 text-wrap  inline-block  bg-chatInputOwnBackgroud  rounded-xl text-white ">
                    {{
                      item.message
                    }}
                  </p>
                </div>
              </div>
              <div class="m-0.5">
                <a-avatar :src=item.avator
                          class="w-14 h-14 "
                          size="large">
                </a-avatar>
              </div>

            </div>
          </div>
          <!--        其他人-->
          <div v-else>
            <div class="flex  mb-3">
              <div class="m-0.5">
                <a-avatar :src="item.avator"
                          class="w-14 h-14 "
                          size="large">
                </a-avatar>
              </div>
              <div class="w-4/6">
                <div>{{ item.name }}</div>
                <div class="min-w-10 text-wrap  inline-block bg-chatInputOtherBackgroud rounded-xl text-black p-2.5">{{
                    item.message
                  }}
                </div>
              </div>
            </div>
          </div>
        </template>

      </div>

      <div class="flex m-1 ">
        <a-textarea
            v-model:value="textareaVal"
            :auto-size="{ minRows: 1, maxRows: 2 }"
            auto-size
            class="textarea w-11/12 mr-2 mt-1 max-[320px]:w-full h-0.5 text-base p-1 border-solid border-1 border-indigo-100 mb-5"
            placeholder="请输入聊天内容"
        />
        <div
            class=" w-12 h-10   leading-10 rounded-full bg-blue-500 text-center hover:bg-blue-400  *:hover:text-white   transition-all  ease-in-out delay-80"
            @click="sendMsg">
          <span class="icon-[material-symbols--send] textNoActiveStyle text-white"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
  width: 5px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #888;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.custom-scrollbar::-webkit-scrollbar-thumb:horizontal {
  background: #888;
}

.custom-scrollbar::-webkit-scrollbar-thumb:horizontal:hover {
  background: #555;
}

.textarea::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.textarea::-webkit-scrollbar-thumb {
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  background-color: #c3c3c3;
}

.textarea::-webkit-scrollbar-track {
  background-color: transparent;
}


</style>